package com.hsylient.javase.chapter12.demo04;

import java.net.URI;
import javax.websocket.ClientEndpoint;
import javax.websocket.CloseReason;
import javax.websocket.ContainerProvider;
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.WebSocketContainer;

@ClientEndpoint
public class MyWebSocketClient {

    private Session session;

    @OnOpen
    public void onOpen(Session session) {
        this.session = session;
        System.out.println("Connected to server");
    }

    @OnMessage
    public void onMessage(String message, Session session) {
        System.out.println("Received message: " + message);
    }

    @OnError
    public void onError(Throwable e) {
        e.printStackTrace();
    }

    @OnClose
    public void onClose(CloseReason reason) {
        System.out.println("Disconnected from server: " + reason.getReasonPhrase());
    }

    public void sendMessage(String message) {
        this.session.getAsyncRemote().sendText(message);
        System.out.println("Sent message: " + message);
    }

    public static void main(String[] args) {
        String uri = "ws://localhost:8080/mywebsocketendpoint";
        try {
            WebSocketContainer container = ContainerProvider.getWebSocketContainer();
            MyWebSocketClient client = new MyWebSocketClient();
            container.connectToServer(client, URI.create(uri));
            client.sendMessage("Hello, server!");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}